<?php


namespace App\Http\Repositories\Admin\Product;

use App\Exceptions\ApiException;
use App\Models\Admin\Models\MemberModel;
use App\Http\Repositories\BaseRepository;
use App\Models\Admin\AdminRedis;
use App\Models\Admin\Models\SkuInfoModel;
use App\Models\Admin\Models\SkuModel;
use App\Models\Admin\Models\SpuModel;
use Illuminate\Support\Facades\Redis;

class SpuRepository extends BaseRepository
{
    public $spu;
    public function __construct(SpuModel $spu)
    {
        $this->spu = $spu;
    }

    /**
     * 添加
     * @param $data
     * @return array
     */
    public function addSpu($data)
    {
        return $this->spu->addSpu($data);
    }

    public function getSpuList($data)
    {
        return $this->spu->getSpuList($data);
    }

    /**
     * 删除
     * @param $data
     * @return string[]
     */
    public function delSpu($data)
    {
        $id = explode(',', $data['ids']);
        $success = 0;
        $fail = 0;
        $message = '';

        foreach ($id as $k => $v) {
            $spu = $this->spu->find($v);
            if (empty($spu)) {
                $fail ++;
                $message .= '第'.($k+1).'个删除失败的原因:数据不存在;';
            } else {
                $success ++;
                $sku_ids = $spu->sku()->pluck('id')->toArray();
                (new SkuInfoModel())->whereIn('product_sku_id', $sku_ids)->delete();

                $spu->sku()->delete();
                $spu->delete();
            }
        }

        return ['message' => '成功删除'.$success.'个;失败'.$fail.'个;'.$message];

    }

    /**
     * 获取详情
     * @param $data
     * @return array|mixed
     */
    public function getSpuInfo($data)
    {
        is_real_exists(@$data['id']) && $where['id'] = $data['id'];
        is_real_exists(@$data['spu']) && $where['spu'] = $data['spu'];

        return $this->spu->getSpuInfo($where ?? []);
    }

    /**
     * 编辑状态
     * @param $data
     * @return array
     */
    public function editSpuStatus($data)
    {
        $ids = explode(',', $data['ids']);

        $update['status'] = $data['operate_type'] == 1 ? $this->spu::YES_STATUS : $this->spu::NO_STATUS;

        foreach ($ids as $k => $v) {
            $where['id'] = $v;
            $this->spu->editItem($where, $update);
        }

        return [];
    }

    /**
     * 编辑
     * @param $data
     * @return array
     * @throws ApiException
     */
    public function editSpu($data)
    {
        $spu = $this->spu->find($data['id']);
        if (is_null($spu))
            throw new ApiException(ApiException::ERROR_DATA_NOT_EXISTS);
        $spu->update($data);

        if (is_real_exists(@$data['sku'])) {
            (new SkuModel())->updateOrCreateTable($data['sku']);
        }

        if (is_real_exists(@$data['sku']['sku_info'])) {
            (new SkuInfoModel())->updateOrCreateTable($data['sku']['sku_info']);
        }

        return [];
    }
}
